package com.webull.information.center.carwler.common.util.news.detection;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.webull.framework.util.UtilDate;
import com.webull.information.center.carwler.common.model.NewsDetection;
import com.webull.information.center.carwler.common.util.jsoup.HttpJsoupClient;

@Component
public class DetectionBloombergList implements DetectionList {
	private final Logger logger = LogManager.getLogger(getClass());
	private @Autowired
    HttpJsoupClient htmlPrase;

	private static final String R_URL = "https://www.bloomberg.com/quote/";

	// String url2 = "https://www.bloomberg.com/quote/AAPL:US";
	// url2 = "https://www.bloomberg.com/quote/000001:CH";
	@Override
	public List<NewsDetection.DetectionResult> parseNewsList(NewsDetection.Detection ticker) {
		String url = R_URL + ticker.getsSymbol() + ":" + ticker.getsExchange();
		Document doc = htmlPrase.parseDocumentFromUrl(url, true);
		if (doc == null) {
			logger.warn("DetectionBloombergList parseNewsList parse url:{} ,doc is null!!", url);
			return null;
		}
		return parseNewsList(ticker, doc);
	}

	private List<NewsDetection.DetectionResult> parseNewsList(NewsDetection.Detection ticker, Document doc) {
		List<NewsDetection.DetectionResult> result = new ArrayList<>();

		// 美股新闻页面
		Optional.ofNullable(doc.select("div[data-group=company-news]").first())//
				.map(v -> v.getElementsByTag("article"))//
				.ifPresent(v -> {
					v.forEach(v0 -> {
						try {
							NewsDetection.DetectionResult item = new NewsDetection.DetectionResult(ticker);
							Date newsTime = Optional.ofNullable(v0.getElementsByTag("time").first())
									.map(v2 -> StringUtils.stripToNull(v2.attr("datetime")))//
									.map(v2 -> UtilDate.parse(v2, 0, "yyyy-MM-dd'T'HH:mm:ss")).orElse(null);
							item.setNewsTime(newsTime);
							Optional.ofNullable(v0.select("a.news-story__url").first()).ifPresent(v2 -> {
								item.setUrl(v2.absUrl("href"));
								if (item.getUrl() != null)
									item.setUrlMd5(HttpJsoupClient.finishingMd5Url(item.getUrl() + item.getsSource()));
								item.setTitle(v2.text());
							});
							if (item.getNewsTime() == null)
								item.setNewsTime(new Date());
							result.add(item);
						} catch (Exception e) {
							logger.warn("DetectionBloombergList error:{}", e);
						}
					});
				});

		return result;
	}

}
